package com.ly.hotel.view.fragments;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

import com.ly.hotel.common.MyLogsManager;
import com.ly.hotel.msgevent.SendLogEvent;

import de.greenrobot.event.EventBus;
import android.app.Fragment;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;

public abstract class BaseFragment extends Fragment{
	public String className = null;
	public abstract boolean onKeyDown(int keyCode, KeyEvent event);
	public abstract boolean setClassName(String name);
	
	@Override
	public void onSaveInstanceState(Bundle outState) {
	    super.onSaveInstanceState(outState);
	    /* 解决可能出现的如下错误
	     * Can not perform this action after onSaveInstanceState at android.app.FragmentManagerImpl.checkStateLoss*/ 
	    invokeFragmentManagerNoteStateNotSaved();
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	private void invokeFragmentManagerNoteStateNotSaved() {
	    /**
	     * For post-Honeycomb devices
	     */
	    if (Build.VERSION.SDK_INT < 16) {
	    	//4.0.3以下
	        return;
	    }
	    try {
	        Class cls = getClass();
	        if(cls != null && cls.getSimpleName() != null){
		        do {
		            cls = cls.getSuperclass();
		            if(cls == null){
		            	Log.d("DLOutState", "不需要保存");
		            	return;
		            }
		        } while (!"Activity".equals(cls.getSimpleName()));
		        Field fragmentMgrField = cls.getDeclaredField("mFragments");
		        fragmentMgrField.setAccessible(true);
	
		        Object fragmentMgr = fragmentMgrField.get(this);
		        cls = fragmentMgr.getClass();
	
		        Method noteStateNotSavedMethod = cls.getDeclaredMethod("noteStateNotSaved", new Class[] {});
		        noteStateNotSavedMethod.invoke(fragmentMgr, new Object[] {});
		        Log.d("DLOutState", "Successful call for noteStateNotSaved!!!");
	        }
	    } catch (Exception ex) {
	        Log.e("DLOutState", "Exception on worka FM.noteStateNotSaved", ex);
	    }
	}
	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		
		String content=null;
		content = MyLogsManager.fixFragmentClassName(className);
		if(content != null){
			EventBus.getDefault().post(new SendLogEvent("ACTION" + "\t" + content));
		}
		
	}
	
	
};
